import datetime
import random

from django.core.mail import send_mail
from django.template.loader import render_to_string

from app.models import Email
from app.statusenum import EmailSendStatusEnum
from project import settings


def send_verification_code(email, send_type, link=None, user_name=None):
    """
    发送邮箱验证码
    :param email: 邮箱地址
    :param send_type: 发送类型
    :param link: 邮件内容-链接
    :param user_name: 用户id
    :return: 邮件发送状态
    """
    from_email = settings.EMAIL_FROM
    to_email = email
    code = random.randint(1000, 9999)
    subject = "ACPlatform(学术平台) 这是一封验证邮件..."  # 标题
    message = {}  # 消息
    send_time = datetime.datetime.now()

    if send_type == '0':
        context = {'email': to_email, 'code': code, 'create_time': send_time}
        html_message = render_to_string('active.html', context)  # html消息
    elif send_type == '1':
        context = {'code': code}
        html_message = render_to_string('forget.html', context)  # html消息
    else:
        return EmailSendStatusEnum.FAIL.value

    # 数据库存档
    new_email = Email()
    new_email.email = email
    new_email.code = code
    new_email.time = send_time
    new_email.type = send_type
    new_email.save()

    send_status = send_mail(subject, message, from_email, [to_email], html_message=html_message)

    return send_status
